﻿using CatUtils.Utils.Currency;
using CatUtils.Utils.Currency.IoUtils;
using CatUtils.Utils.Currency.TextUtils;
using CatUtils.Utils.Enhance.Encrypt;
using CatUtils.Utils.Enhance.ThreadTool;
using CatUtils.Utils.SpecialUtils.Html;
using CatUtilsDll.Utils.Currency.TextUtils;
using CatUtilsDll.Utils.Currency.WebUtils;
using HtmlAgilityPack;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CatUtils.Utils.Enhance.Translate.BaiduTranslate
{
    internal class BaiduTranslateUtils
    {
        public static string TempAPPID = "";
        public static string TempKeys = "";

        public static string InitClientInFile(string APPIDFile, string KeysFile)
        {
            return InitClient(FileHelper.ReadAllText(APPIDFile), FileHelper.ReadAllText(KeysFile));
        }

        public static string InitClient(string APPID, string Keys)
        {
            if (APPID == "" || Keys == "")
            {
                return "";
            }
            else
            {
                TempAPPID = APPID;
                TempKeys = Keys;
                return $"&appid={TempAPPID}&sign={TempKeys}";
            }
        }

        public static bool Check()
        {
            if (TempAPPID == "" || TempKeys == "")
            {
                PrintLog.E("未配置APPID 和 Sign，请调用方法InitClient或InitClientInFile进行配置")
                    ;
                return false;
            }
            return true;
        }

        /// <summary>
        /// 翻译文本，关于语言设置可以参考文档： https://api.fanyi.baidu.com/doc/21
        /// </summary>
        /// <param name="q">待翻译文本</param>
        /// <returns></returns>
        public static string TranslateEnToZh(string q)
        {
            return Translate(q, "en", "zh", TextHelper.GetRandom(111111111, 999999999));
        }

        /// <summary>
        /// 翻译文本，关于语言设置可以参考文档： https://api.fanyi.baidu.com/doc/21
        /// </summary>
        /// <param name="q">待翻译文本</param>
        /// <param name="To">翻译为什么语言</param>
        /// <returns></returns>
        public static string TranslateAuto(string q, string To)
        {
            return Translate(q, "auto", To, TextHelper.GetRandom(111111111, 999999999));
        }

        /// <summary>
        /// 翻译文本，关于语言设置可以参考文档： https://api.fanyi.baidu.com/doc/21
        /// </summary>
        /// <param name="q">待翻译文本</param>

        /// <returns></returns>
        public static string TranslateAutoZh(string q)
        {
            return Translate(q, "auto", "zh", TextHelper.GetRandom(111111111, 999999999));
        }

        /// <summary>
        /// 翻译文本，关于语言设置可以参考文档： https://api.fanyi.baidu.com/doc/21
        /// </summary>
        /// <param name="q">待翻译文本</param>
        /// <param name="Form">设置源语言，可查询文档https://api.fanyi.baidu.com/doc/21</param>
        /// <param name="To">翻译为什么语言</param>
        /// <returns></returns>
        public static string Translate(string q, string Form, string To)
        {
            return Translate(q, Form, To, TextHelper.GetRandom(111111111, 999999999));
        }

        public static string HtmlTranslate(string Shtml, string Form, string To, long salt)
        {
            Shtml = HtmlHelper.Decode(Shtml);
            // Console.WriteLine(Shtml);

            HtmlDocument document = HtmlHelper.LoadHtml(Shtml);

            HtmlNodeCollection htmlNodeCollection = HtmlHelper.SelectNodes(document, "//text()[normalize-space()]");
            if (htmlNodeCollection != null)

                foreach (HtmlNode SingleNode in htmlNodeCollection)
                {
                    ThreadSleep.SetSecondClock(1);
                    string NodeContent = SingleNode.InnerText;
                    Console.WriteLine(NodeContent);
                    string TranslateContent = TranslateAuto(NodeContent, "zh");
                    Console.WriteLine(TranslateContent);
                    var newNode = HtmlNode.CreateNode($"<p>{TranslateContent}</p>");
                    SingleNode.ParentNode.ReplaceChild(newNode, SingleNode);
                }

            string Html = document.DocumentNode.InnerHtml;

            Html = HtmlHelper.LightBoxClear(Html, "ajax", "//img");

            Html = HtmlHelper.RemoveLink(Html);
            Html = HtmlHelper.ReplaceAttributesValue(Html, "src", "//img", "/img/", "https://i0.wp.com/game.watch.impress.co.jp/img/");
            Html = HtmlHelper.RemoveUnsafe(Html);

            FileHelper.WriteText("1.html", Html);
            /**

             foreach (var item in HtmlHelper.LoadHtml(Shtml).DocumentNode.Descendants())
            {
                Console.WriteLine("----");
                Console.WriteLine(item.ChildNodes.Count + "item.ChildNodes.Count");
                Console.WriteLine(item.InnerHtml);
            }
             */
            return "";
        }

        /// <summary>
        /// 翻译文本，关于语言设置可以参考文档： https://api.fanyi.baidu.com/doc/21
        /// </summary>
        /// <param name="q">待翻译文本</param>
        /// <param name="Form">设置源语言，可查询文档https://api.fanyi.baidu.com/doc/21</param>
        /// <param name="To">翻译为什么语言</param>
        /// <param name="salt">随机码 数字</param>
        /// <returns></returns>
        public static string Translate(string q, string Form, string To, long salt)
        {
            if (!Check() || q == "")
                return "";

            try
            {
                string API = $"http://api.fanyi.baidu.com/api/trans/vip/translate?q={WebHelper.UrlEncode(q)}&from={Form}&to={To}&appid={TempAPPID}&salt={salt}&sign={CreateSing(q, salt)}";

                string content = WebHelper.HttpPcGet(API);

                Root root = JsonConvert.DeserializeObject<Root>(content);
                string TempContent = "";
                foreach (var item in root.trans_result)
                {
                    TempContent += Transcoding.DeUnicode(item.dst);
                }
                return TempContent;
            }
            catch (Exception ex)
            {
                PrintLog.E(ex);
            }
            return "";
        }

        /// <summary>
        ///创建Sing 格式： appid+q+salt+密钥 MD5
        /// </summary>
        /// <param name="q"></param>
        /// <param name="Salt"></param>
        /// <returns></returns>
        public static string CreateSing(string q, long Salt)
        {
            return Md5Tool.Md5_32(TempAPPID + q + Salt + TempKeys).ToLower();
        }

        public class Trans_resultItem
        {
            /// <summary>
            ///
            /// </summary>
            public string src { get; set; }

            /// <summary>
            /// Pocket Gamer LaunchPad#3将于本周四开始，这里将展示最精彩的游戏
            /// </summary>
            public string dst { get; set; }
        }

        public class Root
        {
            /// <summary>
            ///
            /// </summary>
            public string from { get; set; }

            /// <summary>
            ///
            /// </summary>
            public string to { get; set; }

            /// <summary>
            ///
            /// </summary>
            public List<Trans_resultItem> trans_result { get; set; }
        }
    }
}